import 'dart:math';

class StringUtil {
  /// 随机字符串
  static String random([int length = 6]) {
    const chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890';
    final rnd = Random();
    return String.fromCharCodes(
      Iterable.generate(
        length,
        (_) => chars.codeUnitAt(rnd.nextInt(chars.length)),
      ),
    );
  }

  static bool isEmpty(String? str) {
    return str == null || str.isEmpty;
  }

  static bool isBlank(String? str) {
    return isEmpty(str?.trim());
  }

  static bool isNotEmpty(String? str) {
    return !isEmpty(str);
  }

  static bool isNotBlank(String? str) {
    return !isBlank(str);
  }

  /// 每隔 x位 加 pattern
  static String formatDigitPattern(String text, {int digit = 4, String pattern = ' '}) {
    text = text.replaceAllMapped(RegExp('(.{$digit})'), (Match match) {
      return '${match.group(0)}$pattern';
    });
    if (text.endsWith(pattern)) {
      text = text.substring(0, text.length - 1);
    }
    return text;
  }

  /// 每隔 x位 加 pattern, 从末尾开始
  static String formatDigitPatternEnd(String text, {int digit = 4, String pattern = ' '}) {
    String temp = reverse(text);
    temp = formatDigitPattern(temp, digit: digit, pattern: pattern);
    temp = reverse(temp);
    return temp;
  }

  /// 每隔4位加空格
  static String formatSpace4(String text) {
    return formatDigitPattern(text);
  }

  /// 每隔3三位加逗号, 针对整数, 可负数
  static String formatComma3(dynamic num, {int digit = 3, String pattern = ','}) {
    final str = num.toString().trim();
    final isNegative = str.startsWith('-');
    final res = formatDigitPatternEnd(isNegative ? str.substring(1) : str, digit: 3, pattern: ',');
    return (isNegative ? '-' : '') + res;
  }

  /// 每隔3三位加逗号, 针对double型
  static String formatDoubleComma3(double num, {int digit = 3, String pattern = ','}) {
    final List<String> list = num.toString().split('.');
    final String left = formatComma3(list[0], digit: digit, pattern: pattern);
    final String right = list.length > 1 ? list[1] : '';
    return '$left.$right';
  }

  /// 隐藏自定范围的字符
  static String hideNumber(String phoneNo, {int start = 3, int end = 7, String replacement = '****'}) {
    return phoneNo.replaceRange(start, end, replacement);
  }

  /// 替换
  static String replace(String text, Pattern from, String replace) {
    return text.replaceAll(from, replace);
  }

  /// 拆分
  static List<String> split(String text, Pattern pattern) {
    return text.split(pattern);
  }

  /// 反转
  static String reverse(String text) {
    if (isBlank(text)) return '';
    final StringBuffer sb = StringBuffer();
    for (int i = text.length - 1; i >= 0; i--) {
      sb.writeCharCode(text.codeUnitAt(i));
    }
    return sb.toString();
  }
}
